import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:frontend/reqs/requests.dart';
import 'package:frontend/states/userState.dart';
import 'package:frontend/utils.dart';
import 'package:provider/provider.dart';

class PublishItemPage extends StatefulWidget {
  const PublishItemPage({super.key});

  @override
  _PublishItemPageState createState() => _PublishItemPageState();
}

class _PublishItemPageState extends State<PublishItemPage> {
  TextEditingController _itemNameController = TextEditingController();
  TextEditingController _itemDescriptionController = TextEditingController();
  TextEditingController _itemPriceController = TextEditingController();
  GlobalKey _formKey = GlobalKey<FormState>();
  Uint8List? imgBytes;

  void _setImg(Uint8List bytes) {
    setState(() {
      imgBytes = bytes;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("发布商品"),
      ),
      body: Container(
        padding: const EdgeInsets.all(24),
        child: Column(
          children: [
            ElevatedButton(
                onPressed: () =>
                {
                  pickImage().then((value) {
                    if (value.length >= 64 * 1024) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('图片太大！'),
                        ),
                      );
                    } else {
                      _setImg(value);
                    }
                  })
                },
                child: const Text('选择图片')),
            SizedBox(
              width: 200,
              height: 200,
              child: imgBytes == null
                  ? Image.asset('assets/img/cxk.jpg')
                  : Image.memory(imgBytes!),
            ),
            Form(
              key: _formKey, //设置globalKey，用于后面获取FormState
              autovalidateMode: AutovalidateMode.onUserInteraction,
              child: Column(
                children: <Widget>[
                  TextFormField(
                    autofocus: true,
                    controller: _itemNameController,
                    decoration: InputDecoration(
                      labelText: "物品的名字",
                      hintText: "这将显示在展示页面上",
                      icon: Icon(Icons.question_answer),
                    ),
                    validator: (v) {
                      return v!.trim().isNotEmpty ? null : "物品的名字不能为空";
                    },
                  ),
                  TextFormField(
                    controller: _itemDescriptionController,
                    maxLines: 3,
                    decoration: InputDecoration(
                      labelText: "描述",
                      hintText: "介绍你打算卖出的商品",
                      icon: Icon(Icons.description),
                    ),
                    validator: (v) {
                      return null;
                    },
                  ),
                  TextFormField(
                    controller: _itemPriceController,
                    decoration: InputDecoration(
                      labelText: "价格",
                      hintText: "你打算以什么价格出售",
                      icon: Icon(Icons.price_check),
                    ),
                    validator: (v) {
                      var reg =
                      RegExp(r'^\d+(\.\d+)?$');
                      return reg.hasMatch(v!.trim()) ? null : "必须是合法数字";
                    },
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 28.0),
                    child: Row(
                      children: <Widget>[
                        ElevatedButton(onPressed: () {
                          if (imgBytes == null ) {
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(
                                content: Text('请为你的商品上传一张图片'),
                              ),
                            );
                          } else if ((_formKey.currentState as FormState)
                              .validate()){
                            publishItem(imgBytes!,
                                _itemNameController.text, int.parse(
                                    _itemPriceController.text),
                                _itemDescriptionController.text);
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(
                                content: Text('商品已发布'),
                              ),
                            );
                          }

                        }, child: Text("发布商品")),
                      ],
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

}
